package com.xiaode.interceptor;

import java.time.LocalDateTime;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.redis.Redis;
import com.xiaode.common.constant.Const;
import com.xiaode.exce.EnumError;

/**
 * SysInterceptor之后，说明已经通过
 * 目前时间间隔3秒
 */
public class SysCallFrequencyInterceptor implements Interceptor {
	
    @Override
    public void intercept(Invocation inv) {
        //用来服务之间调用 验证服务的密钥, 密钥通过才放行
        Controller c = inv.getController();
        String serviceId = c.getHeader("serviceId");
        
        int num = 0;
        LocalDateTime time = null;
        if(Redis.use().exists(Const.serverConst.serviceCall + serviceId)) {
        	Kv kv = Redis.use().get(Const.serverConst.serviceCall + serviceId);
        	time = kv.getLocalDateTime("time");//过期时间
        	num = kv.getInt("num");//已请求时间
        	if(num >= 5) {//限制一个周期内请求5次
        		if(LocalDateTime.now().isBefore(time)) {//如今的时间 在 设定的时间 之前
        			c.renderJson(Ret.fail().set("error", EnumError.CALL_FREQUENCY_EXCEED.getObj()));
        			return;
        		}
        		num = 0;
        		time = LocalDateTime.now().plusSeconds(3);
        		kv.set("num", num);
        		kv.set("time", time);
        		Redis.use().set(Const.serverConst.serviceCall + serviceId, kv);
        	}
        }else {
        	time = LocalDateTime.now().plusSeconds(3);
        }
        c.setAttr("serviceId", serviceId);
        
        inv.invoke();
        
        num = num + 1;
        Kv kv = Kv.of("num", num).set("time", time);
		Redis.use().set(Const.serverConst.serviceCall + serviceId, kv);
    }
    
}
